<template>
  <el-dialog 
    class="simple-dialog"
    :title="'【'+tempData.name+'】图片管理'"
    :visible.sync="tempVisible"
    width="1200px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @close="close"
  >
     <el-card shadow="never">
      <div slot="header" ref="topHeader">
        <!-- <el-form :inline="true" style="text-align: center;">
          <el-form-item label="关键字:">
            <el-input style="width: 220px" v-model="filterText" @keypress.native.enter="getList" placeholder="输入名称关键字搜索" clearable/>
          </el-form-item> 
        </el-form> -->
      </div>
      <div v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="4" style="clear:both">
            <el-upload v-permission="['sys:folder:add']"
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headers"
              :on-success="uploadSuccess"
              name="file"
              accept=".jpg,.png,.mp4"
              multiple
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button size="small" type="primary">选择上传</el-button>
              <div slot="tip" class="el-upload__tip" style="color:red;">可上传多个图片</div>
            </el-upload><br>
            <el-button type="success" icon="el-icon-upload" 
              @click="handleUpload" :disabled="uploadList.length == 0" v-permission="['sys:folder:add']">立即上传</el-button><br><br>
            <el-button size="small" type="primary" @click="download" v-permission="['sys:folder:add']">批量下载</el-button>
          </el-col>
          <el-col :span="20" class="imgList">
            <el-col :span="6" v-for="item in tableData" :key="item.id">
              <el-image v-if="item.type == 1"
                style="width: 90%; height: 140px;margin-bottom:15px;"
                :src="$baseUrl+item.url" 
                :preview-src-list="[$baseUrl+item.url]">
              </el-image>
              <video :src="$baseUrl+item.url" controls  v-if="item.type == 2"
                style="width: 90%; height: 140px;margin-bottom:15px;"></video>
              <i class="el-icon-delete delBtn" @click="remove(item)" v-permission="['sys:file:delete']"></i>
            </el-col>
            <el-col v-if="tableData.length == 0">
              <el-empty description="暂无数据"></el-empty>
            </el-col>
          </el-col>
        </el-row>
        
        <!--分頁-->
        <pagination :total="total" :page.sync="listQuery.page" :pageSizes='[12,24,48,60,96]'
        :limit.sync="listQuery.pageSize" @pagination="getList"  v-if="tableData.length != 0"/>
        <!--添加/编辑-->
        <add-edit
            :dialog-visible="addEditVisible"
            :data="addEditData"
            @close="closeDialog"
            @reloadTable="reloadTable"
        />
      </div>
    </el-card>
  </el-dialog>
</template>

<script>
import Pagination from '@/components/Pagination'
import addEdit from '@/views/img/addEdit'
import testsApi from '@/api/system/file'
import {getToken} from '@/utils/auth'
import JSZip from "jszip";
import FileSaver from "file-saver";

export default {
  name: 'file',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    } 
  },
  components: {Pagination, addEdit},
  data() {
    return {
      tempVisible: false,
      loading: false,
      addEditVisible: false,
      customTableHeight: 200,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 12,
        folderId: null
      },
      tableData: [],
      addEditData: {},
      fileList: [],
      uploadUrl:'',
      headers: {
        Authorization: getToken()
      },
      uploadList:[],
      folderId:'',
      tempData:''
    }
  },
  watch: {
    dialogVisible: function(val) {
      this.tempVisible = val;
    }
  },
  mounted() {
    
    let that = this
    window.onresize = () => {
      //37是box的header的padding，70=(60+10)是顶部的高度
      let tempHeaderHeight = this.$refs.topHeader.offsetHeight + 37 + 95
      let tempHeight = document.body.clientHeight - (106 + tempHeaderHeight)
      if (tempHeight < 300) {
        tempHeight = 300
      }
      that.customTableHeight = tempHeight
    }
    setTimeout(function () {
      const resizeEvent = new Event('resize')
      window.dispatchEvent(resizeEvent)
    }, 100)
    this.uploadUrl = this.$baseUrl + '/system/file/uploadFiles';
    this.folderId = this.$route.query.folderId
    this.getList();
  },
  destroyed() {
    window.onresize = null
  },
  methods: {
    initImgList(row){
      this.folderId = row.id;
      this.tempData = row;
      this.getList()
    },
    getList() {
      this.loading = true;
      this.listQuery.folderId = this.folderId;
      //获取树结构
      testsApi.list(this.listQuery).then(res => {
         console.log(res,"1324")
        this.tableData = res.data || []
        this.total = res.count || 0
        console.log(res.count,'res.count')
        this.loading = false;
      }).catch(() => this.loading = false)
    },  
    // 刷新
    reloadTable(){
      this.getList();
    },
    getFileType(fileName){
      return fileName.substring(fileName.lastIndexOf('.') + 1)
    },
    // 批量下载
    download() {
      var thiz = this;
      var blogTitle = `图片管理`; // 下载后压缩包的命名
      var zip = new JSZip();
      var promises = [];
      let cache = {};
      let arrImg = [];
      for (let i = 0; i < this.tableData.length; i++) {
        arrImg.push({
          path: location.origin + this.$baseUrl + this.tableData[i].url, // 文件链接
          name: this.tableData[i].id // 文件名称
        });
      }
      console.log(arrImg,'arrImg')
      for (let item of arrImg) {
        // item.path为文件链接地址
        const promise = this.getImgArrayBuffer(item.path).then((data) => {
          // 下载文件, 并存成ArrayBuffer对象(blob)
          var fileType = thiz.getFileType(item.path)
          console.log(fileType)
          zip.file(item.name+'.'+fileType , data, { binary: true }); // 逐个添加文件
          cache[item.name] = data;
          console.log(cache[item.name],'cache[item.name]')
        });
        promises.push(promise);
      }
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then((content) => {
          // 生成二进制流
          FileSaver.saveAs(content, blogTitle); // 利用file-saver保存文件  自定义文件名
        });
      }).catch((res) => {
        alert("文件压缩失败");
      });
    },
    //文件以流的形式获取（参数url为文件链接地址）
    getImgArrayBuffer(url) {
      return new Promise((resolve, reject) => {
        //通过请求获取文件blob格式
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (this.status == 200) {
            resolve(this.response);
          } else {
            reject(this.status);
          }
        };
        xmlhttp.send();
      });
    },
    close() {
      this.tempVisible = false;
      this.$emit('close')
    },
    //添加或修改弹窗
    addEdit(row) {
      if (row) {
        this.addEditData = JSON.parse(JSON.stringify(row))
      }else{
        this.addEditData = {
          pid:''
        };
      }
      this.addEditVisible = true
    },
    remove(row) {
      this.$confirm('确定要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        testsApi.remove(row.id).then(res => {
          this.reloadTable()
        })
      })
    },
    closeDialog() {
      this.tempVisible = false
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    uploadSuccess(res,file,fileList){
      this.uploadList = fileList
      console.log( this.uploadList)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    //立即上传
    handleUpload(){
      this.uploadList.forEach((item,i) => {
        var type = 1;
        if(item.raw.type.indexOf("video") > -1){
          type = 2;
        }
        var params = {
          folderId: this.folderId,
          url: item.response.data,
          type: type
        }
        console.log(params)
        testsApi.save(params).then(res => {
          if((i+1) == this.uploadList.length){
            this.$message.success("上传成功")
            this.getList()
            this.fileList = []
            this.uploadList = []
          }
        })
      });
    }
  }
}
</script>
<style scoped >
.treeBtn{
  margin-left: 15px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 800px;
  margin: 0 auto;
}
.simple-dialog>>>.el-dialog{
    margin-top: 5vh !important;
}
.simple-dialog>>>.el-card__body{
  min-height: 570px;
}
.imgList{

}
.delBtn{
    margin-top: -88px;
    vertical-align: middle;
    background: black;
    color: #ffff;
    padding: 5px;
    border-radius: 50%;
    position: relative;
    margin-left: 1px;
    opacity: 0.8;
    cursor: pointer;
}
.delBtn:hover{
    opacity: 0.6;
}

</style>

